package com.huike.controller;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.huike.excel.HospitalManagementExcel;
import com.huike.pojo.Drug;
import com.huike.pojo.Hospital;
import com.huike.pojo.Register;
import com.huike.service.HospitalService;
import com.huike.service.RegisterService;
import com.huike.vo.ExportExcel;
import com.huike.vo.ResultVO;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.FileOutputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RequestMapping(value = "HMC")
@Controller
@ResponseBody
public class HospitalManagementController {
    @Autowired
   private RegisterService registerService;
    @Autowired
    private HospitalService hospitalService;
    @RequestMapping(value = "emps")
    public ResultVO<Register> findAll(){
        List<Register> registers = registerService.findAll();
        return new ResultVO<Register>(registers);
    }
    //住院管理分页查询
    @RequestMapping(value = "Pagination")
public ResultVO<PageInfo> PaginationSearch(Integer id, String registerName, String deptName,
                                           String star, String end,
                                           @RequestParam(value="pageNum",defaultValue = "1") Integer pageNum,
                                           @RequestParam(value="pageSize",defaultValue = "5") Integer pageSize){
        PageHelper.startPage(pageNum,pageSize);
        System.out.println(pageNum+"-----------"+pageSize);
        List<Register> registers = registerService.PaginationSearch(id,registerName,deptName,star,end);
        PageInfo pageInfo = new PageInfo(registers, 5);
        return new ResultVO<PageInfo>(pageInfo);
}
//根据ID查询病人所有信息
@RequestMapping(value = "findByID")
public ResultVO findById(Integer id){
        Register register = registerService.findById(id);
        return  new ResultVO(register);
}
//住院管理增加押金
@RequestMapping(value = "updateAdd_many", method = RequestMethod.POST)
    public ResultVO updateAdd_many(Integer registerId ,Double newDeposit){
    return getResultVO(registerId, newDeposit);
}
//住院管理更改功能
    @RequestMapping(value = "update", method = RequestMethod.POST)
    public ResultVO update(Integer hosR_id, String hosR_name,
                           String hosR_idCar,String hosR_medical,
                           String hosR_phone,Integer hosR_selfPrice,
                           Integer hosR_sex, Integer  hosR_age,
                           Integer hosR_lookDoctor,Integer dept,
                           Integer doctorId,String hosR_remark, String beH_nursePeople ,
                           Integer beH_patBed,String beH_illness){
        registerService.update(hosR_id,hosR_name,hosR_idCar,hosR_medical,hosR_phone,
                               hosR_selfPrice,hosR_sex,hosR_age,hosR_lookDoctor,dept,
                doctorId,hosR_remark);
        hospitalService.update(beH_nursePeople,beH_patBed,beH_illness,hosR_id);

        return  new ResultVO();
    }
    //住院管理添加功能
    @RequestMapping(value = "updateForAdd", method = RequestMethod.POST)
    public ResultVO updateForAdd(Integer hosR_id, String hosR_name,
                           String hosR_idCar,String hosR_medical,
                           String hosR_phone,Integer hosR_selfPrice,
                           Integer hosR_sex, Integer  hosR_age,
                           Integer hosR_lookDoctor, Integer doctorId,
                           String hosR_remark, String beH_nursePeople ,
                           Integer beH_patBed,Double newDeposit,String beH_illness){
        Date date = new Date();//根据现在时间创建一个新时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");//将时间戳转化为年月日格式
        String datestr = sdf.format(date);//将时间戳转化为年月日格式
        registerService.updateForAdd(hosR_id,hosR_name,hosR_idCar,hosR_medical,hosR_phone,
                hosR_selfPrice,hosR_sex,hosR_age,hosR_lookDoctor,
                doctorId,hosR_remark);
        hospitalService.updateForAdd(beH_nursePeople,beH_patBed,beH_illness,hosR_id,datestr);
        return getResultVO(hosR_id, newDeposit);
    }
    //退院功能
    @RequestMapping(value = "deleteAll" ,method = RequestMethod.POST)
    public ResultVO deleteAll(@RequestParam(value="ids[]",required=true)List<Integer> ids){//传入一个ID的集合

        Integer sum =0;
        for (int i =0;i<ids.size();i++){//遍历集合取出值来
            System.out.println(ids.get(i));
           Integer endStatus = hospitalService.findEndStatusById(ids.get(i));
            sum += isEndStatus(endStatus,ids.get(i));

        }
       Integer sun=ids.size()-sum;
        String message = "";
        if (sun==0){
            message="出院成功";
        }
        else {
             message="还有"+sun+"个未结算,先结算";
        }
        return  new ResultVO(ids.size(),message);
    }
    //判断是否是结算状态
    public Integer isEndStatus(Integer check,Integer id ){
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String datestr = sdf.format(date);
    if (check==1){

        registerService.updateStatus(id);
        hospitalService.Discharge(id,datestr);
        return 1;
    }
    else {
        return 0;
    }
    }
//将重复代码提取成一个函数
    private ResultVO getResultVO(Integer hosR_id, Double newDeposit) {
        Hospital hospital =  hospitalService.getHospitalById(hosR_id);
        Double restCost = hospital.getRestCost();
        Double olddeposit = hospital.getDeposit();
        Double deposit = null;
        Double newrestCost = 0.0;
        if (newDeposit==null){
            deposit = olddeposit + 0.0;
            newrestCost = 0.0 + restCost;

        }
        else {
           deposit= olddeposit + newDeposit;
           newrestCost = newDeposit + restCost;
        }


        hospitalService.updateAdd_many(hosR_id,deposit,newrestCost);
        return  new ResultVO();
    }
    //Excel的导出
    @RequestMapping("excelInfo")
    public ResultVO excelInfo(String outStream,Integer id, String registerName, String deptName,
                                    String star, String end){
        List<Register>  list = registerService.PaginationSearch(id,registerName,deptName,star,end);
        List<HospitalManagementExcel>  li = new ArrayList<>();//创建储存想要字段的类
        for(int i = 0;i< list.size();i++){//循环遍历取出想要的值加入储存的集合里
            HospitalManagementExcel hospitalManagementExcel = new HospitalManagementExcel();
            Register register = list.get(i);
            hospitalManagementExcel.setId(register.getId());
            hospitalManagementExcel.setRegisterName(register.getRegisterName());
            hospitalManagementExcel.setBedNumber(register.getHospital().getBedNumber());
            hospitalManagementExcel.setPhone(register.getPhone());
            hospitalManagementExcel.setDeposit(register.getHospital().getDeposit());
            hospitalManagementExcel.setDoctorName(register.getDoctor().getDoctorName());
            hospitalManagementExcel.setDeptName(register.getDepartment()==0?"未分配医生":register.getDept().getDeptName());
            hospitalManagementExcel.setStatus(register.getStatus()==0?"已挂号":"已住院");
            li.add(hospitalManagementExcel);
        }

        String[] headerStr = {"病历号","姓名","床位","联系电话","押金", "主治医生",
                "科室","状态"};//创建想要的表头
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String fileName=outStream +"\\"+ sdf.format(new Date())+"住院办理表.xlsx";//要生成的文件名字
        ExportExcel exportExcel = new ExportExcel();//调用导出工具类
        try{
            OutputStream outputStream = new FileOutputStream(fileName);
            exportExcel.exportExcel(li,outputStream,headerStr);
            outputStream.close();
        }catch (Exception e){
            e.printStackTrace();
            return new ResultVO<>(500,"导出时未知异常");
        }
        return new ResultVO<>(200,"导出成功");
    }
}
